/*
 * @Description: 菜单文件
 * @Author: diyhome
 * @Date: 2020-08-10 10:16
 * @File: menu
*/

#include "menu.h"

uint8_t scan_key() {

    /**
     * 考虑到按键只有两个状态:开/关 -> 1/0
     * 整个遥控器只有8个开关
     * 所以使用一个8位数记录开关状态
     * 从高位到低位的顺序:
     *      面板上的开关为高四位: 左上; 左下; 右上; 右下
     *      侧边开关为低四位: 同上
     */
    uint8_t key_state = 0, state_temp;

    if (HAL_GPIO_ReadPin(TOP_LF_GPIO_Port, TOP_LF_Pin)){
        HAL_Delay(KEY_DOWN_DELAY);
        state_temp = HAL_GPIO_ReadPin(TOP_LF_GPIO_Port, TOP_LF_Pin);
        key_state += (state_temp << 7);
    }

    if (HAL_GPIO_ReadPin(TOP_LB_GPIO_Port, TOP_LB_Pin)){
        HAL_Delay(KEY_DOWN_DELAY);
        state_temp = HAL_GPIO_ReadPin(TOP_LB_GPIO_Port, TOP_LB_Pin);
        key_state += (state_temp << 6);
    }

    if (HAL_GPIO_ReadPin(TOP_RF_GPIO_Port, TOP_RF_Pin)){
        HAL_Delay(KEY_DOWN_DELAY);
        state_temp = HAL_GPIO_ReadPin(TOP_RF_GPIO_Port, TOP_RF_Pin);
        key_state += (state_temp << 5);
    }

    if (HAL_GPIO_ReadPin(TOP_RB_GPIO_Port, TOP_RB_Pin)){
        HAL_Delay(KEY_DOWN_DELAY);
        state_temp = HAL_GPIO_ReadPin(TOP_RB_GPIO_Port, TOP_RB_Pin);
        key_state += (state_temp << 4);
    }

    if (HAL_GPIO_ReadPin(SIDE_LT_GPIO_Port, SIDE_LT_Pin)){
        HAL_Delay(KEY_DOWN_DELAY);
        state_temp = HAL_GPIO_ReadPin(SIDE_LT_GPIO_Port, SIDE_LT_Pin);
        key_state += (state_temp << 3);
    }

    if (HAL_GPIO_ReadPin(SIDE_LB_GPIO_Port, SIDE_LB_Pin)){
        HAL_Delay(KEY_DOWN_DELAY);
        state_temp = HAL_GPIO_ReadPin(SIDE_LB_GPIO_Port, SIDE_LB_Pin);
        key_state += (state_temp << 2);
    }

    if (HAL_GPIO_ReadPin(SIDE_RT_GPIO_Port, SIDE_RT_Pin)){
        HAL_Delay(KEY_DOWN_DELAY);
        state_temp = HAL_GPIO_ReadPin(SIDE_RT_GPIO_Port, SIDE_RT_Pin);
        key_state += (state_temp << 1);
    }

    if (HAL_GPIO_ReadPin(SIDE_RB_GPIO_Port, SIDE_RB_Pin)){
        HAL_Delay(KEY_DOWN_DELAY);
        state_temp = HAL_GPIO_ReadPin(SIDE_RB_GPIO_Port, SIDE_RB_Pin);
        key_state += state_temp;
    }

    return key_state;
}

void Event_Handle_Key() {
    uint8_t key_state = scan_key();

    switch (key_state) {
        case 128:
            key_up();
            break;
        case 64:
            key_down();
            break;
        case 32:
            break;
        case 16:
            break;
        case 8:
            break;
        case 4:
            break;
        case 2:
            break;
        case 1:
            break;
        default:
            break;
    }
}
